// ==UserScript==
// @name			   Better Omega-Day
// @namespace		BOD
// @description	 Better Omega-Day
// @include			http://*.omega-day.*/game/*
// @require  		http://code.jquery.com/jquery-1.8.2.min.js
// @updateURL		http://better-omega-day.googlecode.com/svn/update.js
// @installURL	  http://better-omega-day.googlecode.com/svn/better_od.user.js
// @downloadURL	 http://better-omega-day.googlecode.com/svn/better_od.user.js
// @version			0.8b

// ==/UserScript==

if(typeof(console) === 'undefined') {
    var console = {};
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function(){};
}

$(document).ready(function(){
	BOD.init();	
	
	if(BOD.settings.fix_planet) BOD.fix_planet_list();
	
	if(BOD.search.op == 'planet'){
		if(BOD.settings.geb_menu) BOD.geb_menu();
		if(BOD.settings.sell_planet) BOD.sell_planet();
	} else if(BOD.search.op == 'ptrade'){
		if(BOD.settings.sell_planet) BOD.renew_sell_planet();
	} else if(BOD.search.op == 'fleet'){
		if(BOD.settings.ship_name) BOD.ship_links();
	} else if(BOD.search.op == 'sview'){
		if(BOD.settings.ship_name) BOD.ship_name();
	} else if(BOD.search.op == 'comm'){
		if(BOD.settings.fix_comm) BOD.fix_comm();
	}
	
	if(BOD.debug > 1) console.log(BOD.settings);
});

var BOD = {
	debug: 2,
	userid: $(".statusbar .user").attr('href').substr(-6),
	search: new Object(),
	data: new Object(),
	settings: new Object(),
	init: function(){
		$('<style type="text/css">#BOD_planets {height:auto !important;margin-top:15px !important;}' +
			'#quickjump {width:auto !important;height:auto !important;overflow:visible !important;' +
				'padding:5px !important;border:1px solid #15607F !important;-moz-border-radius:5px !important;border-radius:5px !important;}' + 
			'#quickjump-layer {width:100% !important;height:100% !important;padding:0 !important;margin:-1px 0pt 0pt -1px;' +
				'border:1px solid transparent !important;}' + 
			'#BOD_planets #quickjump table {width:100% !important;}' +
			'#BOD_sell_planet_form td {padding:5px 0;}' +
			'#BOD_gesamt_tr td {border-top:4px double #EEEEEE;}' +
			'#BOD_settings {background-color:#000723;border:1px solid #15607F;border-radius:5px;-moz-border-radius:5px;width:185px;font-size:12px;text-align:center;margin-top:10px;}' +
			'#BOD_settings a {height:16px;display:inline;}' +
			'#BOD_settings a:hover {background-color:#004065;text-decoration:none;}' +
			'#BOD_settings hr {border-width:0 !important;margin:2px 5px !important;padding:0 !important;height:1px !important;}</style>').appendTo('head');
	
		var querystring = window.location.search.substr(1);
		var pairs = querystring.split("&");
		for(var i = 0; i < pairs.length; i++){
			var keyValuePair = pairs[i].split("=");
			BOD.search[keyValuePair[0]] = keyValuePair[1];
		}

		var body_html = $("body").html();	
		
		if(body_html.match(/Willkommen in Omega-Day/)){
			var keys = GM_listValues();
			for(var i = 0, key = null; key = keys[i]; i++){
				if(key == 'firstrun') continue;
				GM_deleteValue(key);
				if(BOD.debug > 0) console.log('GM_deleteValue(' + key + ')');
			}
		} else if(BOD.search.op == 'planet'){
			BOD.data.minpreis = body_html.match(/minpreis = (\d{1,9})/)[1];
			BOD.data.planetid = body_html.match(/planet_id = (\d{1,9})/)[1];
		}

		BOD.read_settings();
		
		$(".menu").append('<li id="BOD_settings">' +
							'Better Omega-Day<br />' + 
							'<a id="BOD_open_settings" href="javascript:$.globalEval(\'new Dialog(\\\'BOD_dialog\\\');Dialog.get(\\\'BOD_dialog\\\').openAndCenter();\');" style="height:16px;">Settings</a><br />' +
							'<a href="javascript:donix();">Info</a><hr /><a href="http://www.simod.gdra.de/pkr9/" target="_blank">Planetenkonfigurator</a><br />' +
							'<a href="http://www.omega-day.com/game/shipconfigurator/" target="_blank">Schiffskonfigurator</a><hr /><small>v0.8a - &copy; <a href="?op=usershow&welch=1000209">Timmaeh</a></small></li>');
		
		$("#BOD_open_settings").on('click', function(){
			BOD.open_settings($(this).attr('id'));
		});
		
	},
	open_dialog: function(id, title, content){
	
		if($("#BOD_dialog").length > 0){
			if($("#BOB_opener_id").val() != id) $("#BOD_dialog").remove();
			else return;
		}
		
		$("#layout-main").append('<div style="width: 440px; left: 180px; top: 50px; visibility: hidden;" class="box dialog" id="BOD_dialog"><input type="hidden" id="BOD_opener_id" value="' + id + '" /><div class="topleft"></div><div class="topright"></div><div class="bottomleft"></div><div class="bottomright"></div><div class="header" id="BOD_dialog_title"><div class="close" id="BOD_dialog_x"><a href="javascript:Dialog.get(\'BOD_dialog\').closeDialog()">X</a></div><div class="title" id="BOD_dialog_tt">' + title + '</div></div><div class="content" id="BOD_dialog_c">' + content + '</div><div class="footer"><a href="javascript:Dialog.get(\'BOD_dialog\').closeDialog()">Schließen</a></div></div>'); 

	},
	read_settings: function(){
		
		GM_setValue('fix_planet', true);
		GM_setValue('geb_menu', true);
		GM_setValue('sell_planet', true);
		GM_setValue('fix_comm', true);
		
		var sett_arr = GM_listValues();
		
		if(sett_arr.length < 1){
			GM_setValue('firstrun', true);
			sett_arr = GM_listValues();
		}
		
		if(sett_arr.length < 2){		
			GM_xmlhttpRequest({
				method: "GET",
				data: "action=getdata&userid=" + BOD.userid,
				url: "http://www.timmaeh.de/betterod/sync.php",
				onload: function(response){
					var pairs = response.responseText.split("&");
					for(var i = 0; i < pairs.length; i++){
						var keyValuePair = pairs[i].split("=");
						if(keyValuePair[0] == 'message' || keyValuePair[0] == 'error'){
							alert(keyValuePair[1]);
							break;
						}
						GM_setValue(keyValuePair[0], keyValuePair[1]);
					}
				}
			});
			sett_arr = GM_listValues();
		}
		
		$.each(sett_arr, function(index, sett){
			BOD.settings[sett] = GM_getValue(sett);
			BOD.settings.ship_name = true;
		});

		if(BOD.settings.firstrun){
			alert('Herzlichen Glückwunsch, du verwendest jetzt Better Omega-Day!');
			GM_setValue('firstrun', false);
		}
	},
	open_settings: function(id){
		var output = '<table>';
			output += '<tr><td><input type="checkbox" name="fix_comm" value="true" '
				output += (BOD.settings.fix_comm) ? 'checked="ckecked"' : '';
				output += '/></td><td>Comm-Box fixen</td>';
			output += '<tr><td><input type="checkbox" name="fix_planet" value="true" '
				output += (BOD.settings.fix_planet) ? 'checked="ckecked"' : '';
				output += '/></td><td>Planetenliste fixen</td>';
			output += '<tr><td><input type="checkbox" name="geb_menu" value="true" '
				output += (BOD.settings.geb_menu) ? 'checked="ckecked"' : '';
				output += '/></td><td>Gebäudeliste fixen</td>';
			output += '<tr><td><input type="checkbox" name="sell_planet" value="true" '
				output += (BOD.settings.sell_planet) ? 'checked="ckecked"' : '';
				output += '/></td><td>"Planet verkaufen" fixen</td>';
			output += '<tr><td colspan="2"><input id="BOD_settings_save" type="button" class="tablebutton" value="Einstellungen speichern" /></td>';
			output += '</table>';
		BOD.open_dialog(id, 'Better Omega-Day - Settings', output);
		
		$("#BOD_settings_save").on('click', function(){
			var settings_string = $("#BOD_dialog :input").serialize();
			BOD.save_settings(settings_string);
			location.reload();
		});
	},
	save_settings: function(settings_string){
		alert(settings_string);
		GM_setValue('fix_planet', true);
		GM_setValue('geb_menu', true);
		GM_setValue('sell_planet', true);
		GM_setValue('fix_comm', true);
	},
	fix_planet_list: function(){
		var menu = $("ul.menu");
		$(menu).attr('id', 'BOD_menu');
		$(menu).find("ul.planets").attr('id', 'BOD_planets');
		
		$(menu).find("li.favourites").remove();
		$("#BOD_planets li.label").remove();
	},
	sleep: function(ms){
		var dt = new Date();
		dt.setTime(dt.getTime() + ms);
		while (new Date().getTime() < dt.getTime());
	},
	sell_planet: function(){
		$("a[href='javascript:planetVerkauf()']").attr('id', 'BOD_sell_planet').attr('href', "javascript:$.globalEval('new Dialog(\\\'BOD_dialog\\\');Dialog.get(\\\'BOD_dialog\\\').openAndCenter();');");
		
		$("#BOD_sell_planet").on('click', function(){
			BOD.open_dialog($(this).attr('id'), 'Planet verkaufen', '<form action="?op=ptrade&verkauf=' + BOD.data.planetid +
				'&sell=sell" method="post" name="Formular7">' + 
				'<input type="hidden" value="' + BOD.data.planetid + '" name="planetid">' + 
				'<input type="hidden" value="' + BOD.data.minpreis + '" name="prizze" id="prizze">' + 
				'<table id="BOD_sell_planet_form" width="100%" cellspacing="0">' +
				'<tr><td></td><td align="right">Grundpreis:</td><td><input type="text" class="tableinput" value="' + BOD.data.minpreis + '" id="verkaufenpreis" disabled="disabled" readonly="readonly"></td><td align="left">zzgl. Steuer</td></tr>' + 
				'<tr><td style="padding:0;font-size:22px;font-weight: bold;">+</td><td align="right">Zuschlag:</td><td><input type="text" class="tableinput" value="0" id="BOD_zuschlag"></td><td align="left">zzgl. Steuer</td></tr>' + 
				'<tr id="BOD_gesamt_tr"><td style="padding:0;font-size:22px;font-weight: bold;">=</td><td align="right">Gesamtpreis:</td><td><input type="text" class="tableinput" value="' + BOD.data.minpreis + '" id="BOD_gesamtpreis"></td><td align="left">zzgl. Steuer</td></tr>' + 
				'<tr><td></td><td align="right">An Spieler:</td><td><input type="text" class="tableinput" value="Alle" name="diran" id="diran"></td><td align="left"></td></tr>' +
				'<tr><td colspan="2"></td><td align="center"><input type="submit" class="tablebutton" value="Anbieten" name="Abschicken"></td><td></td></tr>' +
				'</table></form>' + 
				'<br /><p style="width:250px;margin-left:95px;">Du kannst einen Planeten <font class="BOD_2much">maximal</font> für das <font class="BOD_2much">7 fache des Mindestpreises</font> verkaufen!</p>');
			
			$("#BOD_zuschlag").on('keyup', function(){
				var zuschlag = $("#BOD_zuschlag").val();
				zuschlag = zuschlag.replace(/\D/g, '');
				if(zuschlag == '') zuschlag = 0;
				var gesamtpreis = parseInt(BOD.data.minpreis) + parseInt(zuschlag);
				var maximalpreis = parseInt(BOD.data.minpreis) * 7;
				$("#BOD_gesamtpreis, #prizze").val(gesamtpreis);
				
				$("#BOD_gesamtpreis, #BOD_zuschlag").css('color', '#CCCCFF');
				$(".BOD_2much").css('color', '#EEEEEE');
					
				if(gesamtpreis > maximalpreis){
					$("#BOD_gesamtpreis, .BOD_2much").css('color', 'red');
					$("#prizze").val(maximalpreis);
				} else if(gesamtpreis < parseInt(BOD.data.minpreis)){
					$("#BOD_zuschlag").css('color', 'red');
					$("#prizze").val(BOD.data.minpreis);
				}
			});
			
			$("#BOD_gesamtpreis").on('keyup', function(){
				var gesamtpreis = $("#BOD_gesamtpreis").val();
				gesamtpreis = gesamtpreis.replace(/\D/g, '');
				if(gesamtpreis == '') gesamtpreis = 0;
				var zuschlag = parseInt(gesamtpreis) - parseInt(BOD.data.minpreis);
				var maximalpreis = parseInt(BOD.data.minpreis) * 7;
				$("#BOD_zuschlag").val(zuschlag);
				$("#prizze").val(gesamtpreis);
				
				$("#BOD_gesamtpreis, #BOD_zuschlag").css('color', '#CCCCFF');
				$(".BOD_2much").css('color', '#EEEEEE');
				
				if(gesamtpreis > maximalpreis){
					$("#BOD_gesamtpreis, .BOD_2much").css('color', 'red');
					$("#prizze").val(maximalpreis);
				} else if(gesamtpreis < parseInt(BOD.data.minpreis)){
					$("#BOD_zuschlag").css('color', 'red');
					$("#prizze").val(BOD.data.minpreis);
				}
			});
		});
		
	},
	renew_sell_planet: function(){
		$("a[href^='javascript:renewplanetoffer']").each(function(){
			var rel = $(this).attr('href').substr(28);
			$(this).addClass('BOD_renew_sell_planet').attr('rel', rel).attr('href', "javascript:$.globalEval('new Dialog(\\\'BOD_dialog\\\');Dialog.get(\\\'BOD_dialog\\\').openAndCenter();');");
		});
		
		$(".BOD_renew_sell_planet").on('click', function(){
			
			var data = $(this).attr('rel').split(', ');
			data[2] = data[2].substr(1, data[2].length-3);
			
			BOD.open_dialog($(this).attr('id'), 'Planet verkaufen', '<form action="?op=ptrade&renew=renew" method="post" name="Formular7">' + 
				'<input type="hidden" value="' + data[0] + '" name="renewid">' +  
				'<input type="hidden" value="' + data[1] + '" name="new_price" id="prizze">' +  
				'<table id="BOD_sell_planet_form" width="100%" cellspacing="0">' +
				'<tr><td></td><td align="right">Alter Preis:</td><td><input type="text" class="tableinput" value="' + data[1] + '" id="verkaufenpreis" disabled="disabled" readonly="readonly"></td><td align="left">zzgl. Steuer</td></tr>' + 
				'<tr><td style="padding:0;font-size:22px;font-weight: bold;">+</td><td align="right">Zuschlag:</td><td><input type="text" class="tableinput" value="0" id="BOD_zuschlag"></td><td align="left">zzgl. Steuer</td></tr>' + 
				'<tr id="BOD_gesamt_tr"><td style="padding:0;font-size:22px;font-weight: bold;">=</td><td align="right">Neuer Preis:</td><td><input type="text" class="tableinput" value="' + data[1] + '" id="BOD_gesamtpreis"></td><td align="left">zzgl. Steuer</td></tr>' + 
				'<tr><td></td><td align="right">An Spieler:</td><td><input type="text" class="tableinput" value="' + data[2] + '" name="new_target" id="diran"></td><td align="left"></td></tr>' +
				'<tr><td colspan="2"></td><td align="center"><input type="submit" class="tablebutton" value="Anbieten" name="Abschicken"></td><td></td></tr>' +
				'</table></form>');
			
			$("#BOD_zuschlag").on('keyup', function(){
				var zuschlag = $("#BOD_zuschlag").val();
				zuschlag = zuschlag.replace(/[^0-9-]/g, '');
				zuschlag = zuschlag.substr(0, 1) + zuschlag.substr(1, zuschlag.length-1).replace(/-/g, '');
				if(zuschlag == '' || zuschlag == '-') zuschlag = 0;
				var gesamtpreis = parseInt(data[1]) + parseInt(zuschlag);
				$("#BOD_gesamtpreis, #prizze").val(gesamtpreis);
			});
			
			$("#BOD_gesamtpreis").on('keyup', function(){
				var gesamtpreis = $("#BOD_gesamtpreis").val();
				gesamtpreis = gesamtpreis.replace(/\D/g, '');
				if(gesamtpreis == '') gesamtpreis = 0;
				var zuschlag = parseInt(gesamtpreis) - parseInt(data[1]);
				$("#BOD_zuschlag").val(zuschlag);
				$("#prizze").val(gesamtpreis);
			});
		});
		
	},
	geb_menu: function(){
		var geb_menu = $("#1000").parentsUntil('div', 'table');
		$(geb_menu).attr('id', 'BOD_geb_menu');
		
		var id_rules = new Array('#1003;#1016, #1017',
								 '#1005;#1006, #1025',
								 '#1008;#1018, #1019',
								 '#1007;#1014, #1031',
								 '#1000;#1046, #1053',
								 '#1002;#1009;#1010;#1022;#1023, #1037, #1054',
								 '#1027;#1028',
								 '#1001;#1011;#1015;#1038',
								 '#1035;#1051',
								 '#1032;#1034',
								 '#1042;#1044, #1043',
								 '#1004;#1052',
								 '#1013;#1020',
								 '#1013, #1020;#1048, #1040, #1024, #1029');
		
		$.each(id_rules, function(index, rule){
			var steps = rule.split(';');
			var found = 0;
			steps.reverse();
			$.each(steps, function(step, id_list){			
				if(found == 0){
					if($(id_list).length > 0){
						if(BOD.debug > 1) console.log('FOUND:', id_list);
						found++;
					} else if(BOD.debug > 1){
						console.log('NOT FOUND:', id_list);
					}
				} else {
					if(BOD.debug > 1) console.log('DELETE:', id_list);
					if($(id_list).length > 0) $(id_list).remove();
				}
			});
		});
		
		var geb_json = new Object();
		
		$(geb_menu).find('img').each(function(index, Element){
			var id = $(this).attr('id');
			
			var curr_geb_json = new Object();
			var attrs = $(this)[0].attributes;
			for(var i = 0; i < attrs.length; i++) curr_geb_json['g' + attrs[i].nodeName] = attrs[i].nodeValue;
			
			geb_json[id] = curr_geb_json;
			
		});
		
		$(geb_menu).html('');
		$.each(geb_json, function(index, curr_geb_json){
			var attributes = new Array();
			$.each(curr_geb_json, function(key, value){
				attributes.push(key.substr(1) + '="' + value + '"');
			});
			$(geb_menu).append('<a onfocus="if(document.all) this.blur()" href="javascript:donix();"><img ' + attributes.join(' ') + ' /></a>');
		});
	},
	ship_links: function(){
		$("a[href^='?op=sview&shipid=']").each(function(index){
			var link = $(this).attr('href') + '&index=' + $(this).parent().next().find("a").attr('href').substr(16);
			$(this).attr('href', link);
		});
	},
	ship_name: function(){
		$("#layout-main").find(".box:first-child").find("td").attr("id", "BOD_ship_name");
		var old_name = $("#BOD_ship_name").children("b").html().substr(7);
		$("#BOD_ship_name").children("b").html('Schiff:&nbsp;&nbsp;<form id="BOD_set_new_ship_name" action="?op=sview&shipid=' + BOD.search.shipid + '" method="POST"><input type="text" id="BOD_new_ship_name" class="tableinput" value="' + old_name + '" /> <input type="submit" class="tablebutton" value="Umbenennen" /></form>');
		
		$("#BOD_set_new_ship_name").on('submit', function(event){
			var new_name = $("#BOD_new_ship_name").val();
			if(old_name != new_name){
				$.post("?op=orbit&index=" + BOD.search.index + "&rename=rename", 
					   {neuname: new_name, ships: BOD.search.shipid},
					   function(){ location.reload(true); });
			}
			event.preventDefault();
		});   
	},
	fix_comm: function(){
		$("div.box").attr("id", "BOD_comm");
		var comm_box = $("#BOD_comm table.tabletrans").find("form[action='?op=comm']")[0];
		$(comm_box).children("div[align='center']").css("height", "auto");
		$("#BOD_comm > div > div[align='center']").css("height", "auto");
	}
}